unit rutrans;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils;

function Uncode(const S1:String):string;
function RusTranslateUCS2UTF8(const src:String):string;

implementation
function Uncode(const S1:String):string;
var
  i: Integer;
  s2: String;
  a,b,c,d: Char;
begin
  i:=1;s2:='';
    while i<=length(s1) do
    begin
      a:=s1[i];
      if i<length(s1) then b:=s1[i+1] else b:=#0;
      if i<length(s1)-1 then c:=s1[i+2] else c:=#0;
      if i<length(s1)-2 then d:=s1[i+3] else d:=#0;
      a:=chr(StrToIntDef('$'+a+b,0));
      b:=chr(StrToIntDef('$'+c+d,0));
      s2:=s2+b+a;
      i:=i+4;
    end;
    Result:=UTF8Encode(s2);
    if Result=s2 then Result:=RusTranslateUCS2UTF8(s2);
end;

function RusTranslateUCS2UTF8(const src: String): string;
//partially taken from ustrings.inc fpc
var
  s: String;
  pd:PWord;
  i: Integer;
begin
  s:=src;
  while (length(s) mod 4)>0 do s:=s+#0;
  i:=1;Result:='';
  while i<length(s) do
  begin
    pd:=@s[i];
    if hi(pd^)=0 then
    begin
      if lo(pd^)<$7F then Result:=Result+chr(lo(pd^)) else
        Result:=Result+chr($c0 or (pd^ shr 6))+chr($80 or (pd^ and $3f));
    end else
    if hi(pd^)<7 then
      Result:=Result+chr($c0 or (pd^ shr 6))+chr($80 or (pd^ and $3f))
    else
    Result:=Result+'?';
    i:=i+2;
  end;
end;


end.

